package com.yuanzong.wuliu.common.utils.tree;

import org.springframework.beans.BeanUtils;

import java.util.*;

public final class ObjectTreeConverter {

    /**
     * 将树形ObjectTree转换成ObjectTree列表
     *
     * @param objectList
     * @param <E>
     * @return
     */
    public static <E, I> List<ObjectTree<E>> convert(List<E> objectList, Set<I> selectedIds) {
        if (objectList == null || objectList.size() <= 0) {
            return new ArrayList<>();
        }
        List<ObjectTree<E>> objectEntryList = new ArrayList<>();
        for (E object : objectList) {
            objectEntryList.add(ObjectTree.build(object, selectedIds));
        }
        return objectEntryList;
    }

    /**
     * 将ObjectTree列表转成树形ObjectTree
     *
     * @param objectList 需要转换的列表
     * @param topSign    顶节点值
     */
    public static <E> List<ObjectTree<E>> toTree(List<E> objectList, Object topSign) {
        return toTree(objectList, topSign, null, null);
    }

    /**
     * 将ObjectTree列表转成树形ObjectTree
     */
    private static <E, I> List<ObjectTree<E>> toTree(List<E> objectList, Object topSign, Comparator comparator, Set<I> selectedIds) {
        if (objectList == null || objectList.size() <= 0) {
            return new ArrayList<>();
        }
        List<ObjectTree<E>> entryObjectList = convert(objectList, selectedIds);
        List<ObjectTree<E>> entryTreeList = new ArrayList<>();
        for (ObjectTree<E> entryObject : entryObjectList) {
            if (entryObject.equalsParent(topSign)) {
                ObjectTree<E> objectTree = new ObjectTree<>();
                BeanUtils.copyProperties(entryObject, objectTree);
                objectTree.setId(entryObject.getId());
                objectTree.setParentId(entryObject.getParentId());
                objectTree.setEntry(entryObject.getEntry());
                buildTree(entryObjectList, objectTree, comparator, selectedIds);
                entryTreeList.add(objectTree);
            }
        }
        if (comparator != null) {
            Collections.sort(entryTreeList, comparator);
        }
        return entryTreeList;
    }

    /**
     * 构建ObjectTree对象
     */
    private static <E, I> void buildTree(List<ObjectTree<E>> entryObjectList, ObjectTree<E> treeObject, Comparator comparator, Set<I> selectedIds) {
        List<ObjectTree<E>> children = new ArrayList<>();
        for (ObjectTree<E> entryObject : entryObjectList) {
            if (entryObject.equalsParent(treeObject.getId())) {
                children.add(entryObject);
            }
        }
        if (children.size() > 0) {
            treeObject.setChildren(children);
            if (comparator != null) {
                Collections.sort(children, comparator);
            }
            for (ObjectTree<E> childObjectTree : children) {
                buildTree(entryObjectList, childObjectTree, comparator, selectedIds);
            }
        }
    }

}
